var main = angular.module('main');

main.controller('edit_projectCtrl', ['$scope', 'http', '$stateParams', '$state', function($scope, http, $stateParams, $state) {
    $scope.groupMembers = [];
    $scope.newUserName = "";
    $scope.newRole = "2";


    $scope.project_id = $stateParams.project_id;

    http.post('/project/detail', { project_id: $scope.project_id }).then(function(data) {
        $scope.project = data.data;
        $scope.projectName = $scope.project.name;
        $scope.projectDesc = $scope.project.description;
    });
    http.post('/project/member/list', { project_id: $scope.project_id }).then(function(data) {
        $scope.groupMembers = data.data;
    });

    $scope.addMember = function() {
        var member = { 'username': $scope.newUserName, 'role': $scope.newRole };

        http.post('/project/member/add', { project_id: $scope.project_id, username: member.username, role: member.role }).then(function(data) {
            if (data.code === 0) {
                $scope.groupMembers.push(data.data);
            }
            if (data.code === 1) {
                alert("用户名不存在");
            }
            if (data.code === 3) {
                alert("不能添加自己");
            }
            if (data.code === 4) {
                alert("不能重复添加成员");
            }
            $scope.newUserName = '';
        });

    };
    $scope.deleteMember = function(member) {
        http.post('/project/member/delete', { membership_id: member.id }).then(function(data) {
            if (data.code === 0) {
                var index = $scope.groupMembers.indexOf(member);
                $scope.groupMembers.splice(index, 1);
            }
        });
    };

    $scope.selectChange = function(member) {
        http.post('/project/member/update', { membership_id: member.id, role: member.role }).then(function(data) {});
    };

    $scope.updateProject = function() {
        http.post('/project/update', { project_id: $scope.project_id, name: $scope.projectName, description: $scope.projectDesc })
            .then(function(data) {
                if (data.code === 0) {
                    UIkit.modal.alert("项目更新成功");
                    $state.go('project.projects',{type:'allProject'});
                }
            });
    };

    $scope.deleteProject = function(data) {
        http.post('/project/delete', { project_id: $scope.project_id }).then(function(data) {
            console.log(data);
            if (data.code === 0) {
                $state.go('project.projects.allProject');
            }
            if (data.code === -3) {
                alert("项目删除失败");
            }
        });
    };
}]);